//
//  TableViewController.m
//  Ricky_RefreshControl
//
//  Created by MR-zhang on 15/7/9.
//  Copyright (c) 2015年 Ricky. All rights reserved.
//

#import "NormalViewController.h"
#import "UIScrollView+RCKRefreshControl.h"
#import "RickyRefreshView.h"

@interface NormalViewController () <UITableViewDataSource, UITableViewDelegate>
{
    UITableView *table;
    NSMutableArray *dataArray;
}

@end

@implementation NormalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"NormalRefresh";
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
        [UITableView appearance].estimatedRowHeight = 0;
        [UITableView appearance].estimatedSectionFooterHeight = 0;
        [UITableView appearance].estimatedSectionHeaderHeight = 0;
        if (@available(iOS 11.0,*)) {
            [UIScrollView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            [UITableView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            [UICollectionView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            [UIWebView appearance].scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    
    dataArray = @[].mutableCopy;
    
    table = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    table.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    table.delegate = self;
    table.dataSource = self;
//    table.estimatedRowHeight = 60;
    table.rowHeight = 60;
    [self.view addSubview:table];
    
    [table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellIdentifier"];
    
//    [self handleTableData:^{
//        [table reloadData];
//        [table completeRickyRefreshHeaderWithCompleteType:RickyRefreshCompleteTypeNoData];
//    }];
    
    __weak __typeof(self)weakSelf = self;
    __weak __typeof(table)weakTable = table;
    // 添加顶部刷新控件
    [table addNormalRickyRefreshHeaderViewWithCallBackAction:^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf refreshData:^{
            __strong __typeof(weakTable)strongTable = weakTable;
            [strongTable completeRickyRefreshHeaderWithCompleteType:RickyRefreshCompleteTypeSuccess];
            [strongTable reloadData];
        }];
    }];
    
    // 添加底部加载控件
    [table addNormalRickyRefreshFooterViewWithCallBackAction:^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf addMoreData:^{
            __strong __typeof(weakTable)strongTable = weakTable;
            [strongTable completeRickyRefreshFooterWithCompleteType:RickyRefreshCompleteTypeSuccess];
            [strongTable reloadData];
        }];
    }];
    
//    [table setHeaderRefreshAtBegin:YES];
    
}

- (void)handleTableData:(void(^)())then
{
    dispatch_queue_t queue = dispatch_queue_create("com.Ricky.refresh", NULL);
    dispatch_apply(10, queue, ^(size_t i) {
        [dataArray addObject:[NSString stringWithFormat:@"This is original data %zu", i]];
    });
    
    dispatch_async(dispatch_get_main_queue(), ^{
        !then ? :then();
    });
}

#pragma mark -- table'delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellIdentifier"];
    }
    if (dataArray.count > 0) {
        cell.textLabel.text = dataArray[indexPath.row];
    }
    
    return cell;
}

#pragma mark -- 处理数据
- (void)refreshData:(void(^)())then
{
    if (dataArray.count > 0) {
        [dataArray removeAllObjects];
        [table reloadData];
    }
    
    for (int i=0; i<3; i++) {
        [dataArray addObject:[NSString stringWithFormat:@"This is refresh data %d", i]];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        !then ? : then();
    });
}

- (void)addMoreData:(void(^)())then
{
    NSInteger count = dataArray.count;
    
    for (int i=0; i<2; i++) {
        [dataArray addObject:[NSString stringWithFormat:@"This is refresh data %i", (int)(i+count)]];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        !then ? : then();
    });
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
